package com.wbpay.sdk.formatter;

import android.text.TextUtils;

import com.wbpay.sdk.constant.Constants;
import com.wbpay.sdk.http.Response;
import com.wbpay.sdk.params.User;
import com.wbpay.sdk.utils.Log;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.ByteArrayInputStream;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilderFactory;

/**
 * Created by ck01- on 2017/7/4.
 */

public class UserXmlFormatter extends Formatter<User> {

    private static final String STATE = "you9/state";
    private static final String DESC = "you9/stateDesc";
    private static final String USERNAME = "you9/user/username";
    private static final String GENDAR = "you9/user/gendar";
    private static final String USERKEY = "you9/user/userKey";
    private static final String ID = "you9/user/userID";
    private static final String NICKNAME = "you9/user/nickname";
    private static final String ISVIP = "you9/user/isVIPUser";
    private static final String VIPLEVEL = "you9/user/vipLevel";
    private static final String IDCARD = "you9/user/idcard";

    @Override
    public Response<User> format(String content) {
        return parseLoginResXMl(content);
    }

    private Response<User> parseLoginResXMl(String resultXML) {

        Response<User> response = new Response<User>();
        User user = new User();
        response.setObj(user);
        if (TextUtils.isEmpty(resultXML)) {// 未返回处理结果
            response.setCode(Constants.STATE_TIMEOUT);
            response.setMsg(Constants.CONNECT_TIMEOUT_DESC);
            return null;
        }// 成功返回
        else {
            Map<String, String> map = parse(resultXML);
            // 解析出错
            if (map == null || map.get(STATE) == null) {
                response.setCode(Constants.STATE_SYS_ERR);
                response.setMsg(Constants.SYS_ERR_DESC);
            }// 登陆失败
            else if (!map.get(STATE).equals(Constants.STATE_SUC)) {
                response.setCode(map.get(STATE));
                response.setMsg(map.get(DESC));
            }// 登陆成功
            else {
                user.setUsername(map.get(USERNAME));
                user.setGendar(map.get(GENDAR));
                user.setUserKey(map.get(USERKEY));
                user.setNickName(map.get(NICKNAME));
                user.setVipLevel(map.get(VIPLEVEL));
                user.setIsVipUser(map.get(ISVIP));
                String idcard = map.get(IDCARD);
                if (idcard != null && idcard.trim().length() > 0) {
                    if (idcard.length() == 18) {
                        user.setBirthday(handleBirthday18(idcard));
                    } else if (idcard.length() == 15) {
                        user.setBirthday(handleBirthday15(idcard));
                    } else {
                        user.setBirthday(idcard);
                    }
                } else {
                    user.setBirthday("1990-01-01");
                }
                String birthday = user.getBirthday();
                int year = Integer.parseInt(birthday.substring(0, 4));
                Calendar c = Calendar.getInstance();
                user.setAge(c.get(Calendar.YEAR) - year + "");
                user.setId(Long.parseLong(map.get(ID)) + "");
                // user.setId((Long.parseLong(map.get(ID))+1000000000) + "");
                response.setCode(map.get(STATE));
                response.setMsg(map.get(DESC));
            }
        }
        return response;
    }

    private static String handleBirthday15(String idcard) {
        idcard = "19" + idcard.substring(6, 12);
        String result = idcard.substring(0, 4) + "-" + idcard.substring(4, 6)
                + "-" + idcard.substring(6, 8);
        return result;
    }

    private static String handleBirthday18(String idcard) {
        idcard = idcard.substring(6, 14);
        String result = idcard.substring(0, 4) + "-" + idcard.substring(4, 6)
                + "-" + idcard.substring(6, 8);
        return result;
    }

    private Map<String, String> parse(String xmlStr) {
        if (TextUtils.isEmpty(xmlStr)) {
            return null;
        }
        Element rootElement = null;
        Map<String, String> map = null;
        try {
            rootElement = DocumentBuilderFactory
                    .newInstance().newDocumentBuilder()
                    .parse(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")))
                    .getDocumentElement();
            map = new HashMap<String, String>();
            //解析XML 放入Map
            parse(rootElement.getNodeName(), rootElement, map);
        } catch (Exception e) {
            Log.e(Log.TAG, "根据xml字符串生成Element对象失败 : " + e);
        }
        return map;
    }

    /**
     * 解析XML信息至Map
     * 该方法只适合部分简单XML解析 目前只适合解析注册及登录返回的XML
     *
     * @param elementName 当前节点名称
     * @param element     当前element对象
     * @param map         保存xml的map
     */
    private void parse(String elementName, Element element, Map<String, String> map) {
        if (map == null) {
            map = new HashMap<String, String>();
        }
        //获取子节点列表
        NodeList rootItems = element.getChildNodes();
        //循环获取子节点信息
        for (int i = 0; i < rootItems.getLength(); i++) {
            //节点名称（上一级节点 + 当前节点）
            String curElementName = elementName + "/" + rootItems.item(i).getNodeName();
            //如果该节点下仍有子节点
            if (rootItems.item(i).getChildNodes().getLength() > 1) {
                //递归遍历
                parse(curElementName, (Element) rootItems.item(i), map);
            }//无子节点 put节点值信息
            else {
                map.put(curElementName, rootItems.item(i).getTextContent());
            }
        }
    }
}
